<template>
  <div class="profile-page">
    <div class="container">
      <div class="page-header">
        <h1 class="page-title">个人资料</h1>
        <button class="btn btn-outline refresh-btn" @click="refreshUserData" :disabled="loading">
          <span v-if="loading">刷新中...</span>
          <span v-else>刷新数据</span>
        </button>
      </div>
      
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载用户资料中...</p>
      </div>
      
      <div v-else-if="error" class="error-container">
        <h3>获取资料失败</h3>
        <p>{{ error }}</p>
        <button class="btn btn-primary" @click="fetchUserProfile">重试</button>
      </div>
      
      <div v-else class="profile-container">
        <div class="profile-header">
          <div class="profile-avatar">
            <img v-if="userProfile.avatar" :src="userProfile.avatar" alt="用户头像" />
            <div v-else class="default-avatar" :style="{ background: generateGradient() }">
              {{ userInitial }}
            </div>
          </div>
          
          <div class="profile-info">
            <h2>{{ userProfile.nickName || userProfile.userName }}</h2>
            <p class="join-date">加入时间: {{ formatDate(userProfile.createTime) }}</p>
            <div class="profile-stats">
              <div class="stat-item">
                <div class="stat-value">{{ userProfile.challengeCompleted || 0 }}</div>
                <div class="stat-label">已完成挑战</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ userProfile.points || 0 }}</div>
                <div class="stat-label">碳积分</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ userProfile.carbonReduced || 0 }}kg</div>
                <div class="stat-label">减碳量</div>
              </div>
            </div>
          </div>
          
          <button class="btn btn-outline edit-profile-btn" @click="navigateToSettings">编辑资料</button>
        </div>
        
        <div class="profile-tabs">
          <div 
            class="tab-item" 
            :class="{ 'active': activeTab === 'info' }"
            @click="activeTab = 'info'"
          >
            基本信息
          </div>
          <div 
            class="tab-item" 
            :class="{ 'active': activeTab === 'challenges' }"
            @click="activeTab = 'challenges'"
          >
            参与的挑战
          </div>
          <div 
            class="tab-item" 
            :class="{ 'active': activeTab === 'achievements' }"
            @click="activeTab = 'achievements'"
          >
            成就与证书
          </div>
        </div>
        
        <div class="tab-content">
          <!-- 基本信息 -->
          <div v-if="activeTab === 'info'" class="info-tab">
            <div class="info-card">
              <h3>个人信息</h3>
              <div class="info-item" @click="toggleCatActive(0)">
                <div class="cat-icon">🐱</div>
                <div class="info-label">用户名</div>
                <div class="info-value">{{ userProfile.userName }}</div>
              </div>
              <div class="info-item" @click="toggleCatActive(1)">
                <div class="cat-icon">😺</div>
                <div class="info-label">昵称</div>
                <div class="info-value">{{ userProfile.nickName || '未设置' }}</div>
              </div>
              <div class="info-item" @click="toggleCatActive(2)">
                <div class="cat-icon">😸</div>
                <div class="info-label">性别</div>
                <div class="info-value">{{ getSexText(userProfile.sex) }}</div>
              </div>
              <div class="info-item" @click="toggleCatActive(3)">
                <div class="cat-icon">😹</div>
                <div class="info-label">邮箱</div>
                <div class="info-value">{{ userProfile.email || '未设置' }}</div>
              </div>
              <div class="info-item" @click="toggleCatActive(4)">
                <div class="cat-icon">😻</div>
                <div class="info-label">手机号</div>
                <div class="info-value">{{ userProfile.phone || '未设置' }}</div>
              </div>
              <div class="info-item" @click="toggleCatActive(5)">
                <div class="cat-icon">🙀</div>
                <div class="info-label">个人介绍</div>
                <div class="info-value info-introduction">{{ userProfile.introduce || '暂无介绍' }}</div>
              </div>
            </div>
          </div>
          
          <!-- 参与的挑战 -->
          <div v-else-if="activeTab === 'challenges'" class="challenges-tab">
            <p class="placeholder-message">您参与的挑战将显示在这里</p>
          </div>
          
          <!-- 成就与证书 -->
          <div v-else-if="activeTab === 'achievements'" class="achievements-tab">
            <p class="placeholder-message">您的成就和证书将显示在这里</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserInfo } from '@/utils/auth'

export default {
  name: 'UserProfile',
  data() {
    return {
      loading: true,
      error: null,
      userProfile: {},
      activeTab: 'info',
      activeCatIndex: -1
    }
  },
  computed: {
    userInitial() {
      const name = this.userProfile.nickName || this.userProfile.userName || '';
      if (!name) return '用';
      
      // 如果是中文名，取第一个字
      if (/[\u4e00-\u9fa5]/.test(name)) {
        return name.charAt(0);
      }
      
      // 如果是英文名，取首字母
      return name.charAt(0).toUpperCase();
    }
  },
  created() {
    // 检查是否从设置页面保存过数据
    this.checkForUpdatedData();
    
    // 获取用户资料
    this.fetchUserProfile();
  },
  methods: {
    // 检查是否有来自设置页面的更新
    checkForUpdatedData() {
      const userDataUpdated = localStorage.getItem('userDataUpdated');
      const userDataUpdatedTime = localStorage.getItem('userDataUpdatedTime');
      
      if (userDataUpdated === 'true' && userDataUpdatedTime) {
        // 检查更新时间是否在30秒内
        const updatedTime = parseInt(userDataUpdatedTime);
        const currentTime = new Date().getTime();
        const timeElapsed = currentTime - updatedTime;
        
        if (timeElapsed < 30000) { // 30秒内
          console.log('检测到设置页面刚保存了数据，将强制刷新获取最新数据');
          // 清除标记
          localStorage.removeItem('userDataUpdated');
          localStorage.removeItem('userDataUpdatedTime');
          
          // 刷新数据
          this.refreshUserData();
          return;
        } else {
          // 标记过期，清除
          localStorage.removeItem('userDataUpdated');
          localStorage.removeItem('userDataUpdatedTime');
        }
      }
    },
    // 跳转到设置页面
    navigateToSettings() {
      // 无需缓存用户资料，直接跳转到 settings 页面
      // 系统会在 settings 页面自动获取最新的用户数据
      
      // 跳转到settings页面并指定tab参数为account
      this.$router.push({ path: '/settings', query: { tab: 'account' } });
    },
    
    // 刷新用户数据的方法
    refreshUserData() {
      this.fetchUserProfile(true); // 传入true参数强制刷新
    },
    
    // 修改fetchUserProfile方法，添加forceRefresh参数
    fetchUserProfile(forceRefresh = false) {
      this.loading = true;
      this.error = null;
      
      // 获取本地存储的用户信息
      const localUserInfo = getUserInfo();
      
      // 直接从服务器获取最新数据，不使用缓存
      import('@/api/auth').then(module => {
        if (localUserInfo && localUserInfo.userName) {
          module.getCurrentUserInfo(localUserInfo.userName, forceRefresh || true) // 使用传入的forceRefresh参数或默认使用true
            .then(response => {
              if (response.success && response.data) {
                this.userProfile = {
                  id: response.data.id,
                  userName: response.data.userName,
                  nickName: response.data.nickName,
                  avatar: response.data.avatar,
                  email: response.data.email,
                  phone: response.data.phone,
                  sex: response.data.sex,
                  introduce: response.data.introduce || response.data.extJson || '暂无介绍',
                  status: response.data.status,
                  createTime: response.data.createTime || new Date(),
                  challengeCompleted: response.data.challengeCompleted || 0,
                  points: response.data.points || 0,
                  carbonReduced: response.data.carbonReduced || 0
                };
                console.log('已获取最新数据');
              } else {
                this.error = response.message || '获取用户资料失败';
              }
            })
            .catch(error => {
              console.error('获取用户详情失败:', error);
              this.error = error.message || '获取用户资料失败，请稍后重试';
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          this.error = '用户信息不完整，请重新登录';
          this.loading = false;
        }
      }).catch(error => {
        console.error('加载API模块失败:', error);
        this.error = '系统错误，请稍后重试';
        this.loading = false;
      });
    },
    getSexText(sex) {
      switch (sex) {
        case 1:
          return '男';
        case 2:
          return '女';
        default:
          return '保密';
      }
    },
    formatDate(date) {
      if (!date) return '未知';
      
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      
      return `${year}-${month}-${day}`;
    },
    generateGradient() {
      // 根据用户名生成一个固定的渐变色
      let hash = 0;
      const name = this.userProfile.userName || '';
      
      for (let i = 0; i < name.length; i++) {
        hash = name.charCodeAt(i) + ((hash << 5) - hash);
      }
      
      // 确保哈希值为正
      hash = Math.abs(hash);
      
      // 生成两个颜色
      const hue1 = hash % 360;
      const hue2 = (hash * 7) % 360;
      
      return `linear-gradient(135deg, hsl(${hue1}, 70%, 60%), hsl(${hue2}, 70%, 60%))`;
    },
    toggleCatActive(index) {
      this.activeCatIndex = this.activeCatIndex === index ? -1 : index;
      
      setTimeout(() => {
        if (this.activeCatIndex === index) {
          this.activeCatIndex = -1;
        }
      }, 3000);
    }
  }
}
</script>

<style scoped>
.profile-page {
  padding: 30px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  color: #333;
  margin-bottom: 0;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 300px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(76, 175, 80, 0.1);
  border-radius: 50%;
  border-top-color: #4CAF50;
  animation: spin 1s linear infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-container {
  text-align: center;
  padding: 40px 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.error-container h3 {
  color: #d32f2f;
  margin-bottom: 15px;
}

.profile-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.profile-header {
  display: flex;
  align-items: center;
  padding: 30px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.profile-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 30px;
}

.profile-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 40px;
  font-weight: bold;
}

.profile-info {
  flex: 1;
}

.profile-info h2 {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px 0;
}

.join-date {
  color: #666;
  margin-bottom: 15px;
}

.profile-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #4CAF50;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.edit-profile-btn {
  position: absolute;
  top: 30px;
  right: 30px;
}

.profile-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
}

.tab-item {
  padding: 15px 20px;
  cursor: pointer;
  font-weight: 500;
  color: #666;
  transition: all 0.3s;
  position: relative;
}

.tab-item:hover {
  color: #4CAF50;
}

.tab-item.active {
  color: #4CAF50;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #4CAF50;
}

.tab-content {
  padding: 30px;
}

.info-card {
  background-color: white;
  border-radius: 8px;
  padding: 0;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  animation: card-fade-in 0.5s ease-in-out;
}

@keyframes card-fade-in {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.info-card h3 {
  margin: 0;
  padding: 16px 24px;
  text-align: center;
  color: #262626;
  font-size: 16px;
  font-weight: 600;
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  transition: background-color 0.3s ease;
}

.info-item {
  display: block;
  margin: 0;
  padding: 0;
  border-bottom: 1px solid #e8e8e8;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  cursor: pointer;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item:hover {
  background-color: rgba(76, 175, 80, 0.03);
}

.info-item:hover .info-value {
  transform: scale(1.02);
}

.info-item::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 2px;
  background-color: #4CAF50;
  transform: scaleX(0);
  transition: transform 0.3s ease;
  transform-origin: center;
}

.info-item:hover::after {
  transform: scaleX(1);
}

.cat-icon {
  position: absolute;
  font-size: 24px;
  top: 50%;
  left: -30px;
  transform: translateY(-50%);
  transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  opacity: 0.7;
  user-select: none;
}

.info-item:hover .cat-icon {
  left: 15px;
  transform: translateY(-50%) rotate(15deg);
}

.info-item:active .cat-icon {
  transform: translateY(-50%) scale(1.2);
}

/* 为每个小猫定制不同的动画 */
.info-item:nth-child(2) .cat-icon { animation: cat-bounce 2s infinite; }
.info-item:nth-child(3) .cat-icon { animation: cat-wiggle 3s infinite; }
.info-item:nth-child(4) .cat-icon { animation: cat-spin 4s infinite; }
.info-item:nth-child(5) .cat-icon { animation: cat-jump 3.5s infinite; }
.info-item:nth-child(6) .cat-icon { animation: cat-dance 3s infinite; }
.info-item:nth-child(7) .cat-icon { animation: cat-surprise 5s infinite; }

@keyframes cat-bounce {
  0%, 100% { transform: translateY(-50%); }
  50% { transform: translateY(-65%); }
}

@keyframes cat-wiggle {
  0%, 100% { transform: translateY(-50%) rotate(0); }
  25% { transform: translateY(-50%) rotate(10deg); }
  75% { transform: translateY(-50%) rotate(-10deg); }
}

@keyframes cat-spin {
  0%, 100% { transform: translateY(-50%) rotate(0); }
  50% { transform: translateY(-50%) rotate(360deg); }
}

@keyframes cat-jump {
  0%, 20%, 50%, 80%, 100% { transform: translateY(-50%); }
  40% { transform: translateY(-70%); }
  60% { transform: translateY(-60%); }
}

@keyframes cat-dance {
  0%, 100% { transform: translateY(-50%); }
  25% { transform: translateY(-50%) translateX(-5px); }
  50% { transform: translateY(-60%) translateX(0); }
  75% { transform: translateY(-50%) translateX(5px); }
}

@keyframes cat-surprise {
  0%, 85%, 100% { transform: translateY(-50%) scale(1); }
  90% { transform: translateY(-50%) scale(1.3); }
}

.info-label {
  display: block;
  width: 100%;
  color: #737373;
  font-weight: 500;
  font-size: 14px;
  text-align: center;
  padding: 16px 30px 8px 30px;
  transition: color 0.3s ease;
}

.info-item:hover .info-label {
  color: #4CAF50;
}

.info-value {
  display: block;
  width: 100%;
  color: #262626;
  font-size: 14px;
  font-weight: 400;
  text-align: center;
  padding: 0 0 16px 0;
  transition: all 0.3s ease;
}

.info-introduction {
  white-space: pre-line;
  line-height: 1.5;
  color: #262626;
  text-align: center;
  transition: all 0.3s ease;
}

.info-item:hover .info-introduction {
  color: #444;
}

/* 加载动画 - 为每个信息项添加逐个显示的动画 */
.info-item:nth-child(1) { animation: item-fade-in 0.3s ease-out 0.1s both; }
.info-item:nth-child(2) { animation: item-fade-in 0.3s ease-out 0.2s both; }
.info-item:nth-child(3) { animation: item-fade-in 0.3s ease-out 0.3s both; }
.info-item:nth-child(4) { animation: item-fade-in 0.3s ease-out 0.4s both; }
.info-item:nth-child(5) { animation: item-fade-in 0.3s ease-out 0.5s both; }
.info-item:nth-child(6) { animation: item-fade-in 0.3s ease-out 0.6s both; }

@keyframes item-fade-in {
  from {
    opacity: 0;
    transform: translateX(-10px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 点击小猫时的特效 */
.info-item.cat-active .info-value {
  transform: scale(1.05);
  color: #4CAF50;
}

/* 媒体查询 */
@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    text-align: center;
  }
  
  .profile-avatar {
    margin-right: 0;
    margin-bottom: 20px;
  }
  
  .profile-stats {
    justify-content: center;
  }
  
  .edit-profile-btn {
    position: static;
    margin-top: 20px;
    width: 100%;
  }
  
  .info-item:hover .cat-icon {
    left: 10px;
  }
  
  .info-item:hover .info-value {
    transform: none;
  }
  
  .info-label {
    padding-left: 35px;
  }
}

.placeholder-message {
  text-align: center;
  padding: 30px;
  color: #666;
  font-style: italic;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.btn-primary {
  background-color: #4CAF50;
  color: white;
}

.btn-primary:hover {
  background-color: #3d8b40;
}

.btn-outline {
  background-color: white;
  color: #4CAF50;
  border: 1px solid #4CAF50;
}

.btn-outline:hover {
  background-color: #f1f8f1;
}

.refresh-btn {
  padding: 6px 12px;
  font-size: 14px;
}
</style> 